package com.youlu.campus.website.service.impl;

import com.youlu.campus.website.common.enums.PlatformType;
import com.youlu.campus.website.entity.CompanyDynamicDetail;
import com.youlu.campus.website.entity.CompanyDynamicDetailPageQuery;
import com.youlu.campus.website.repositories.CompanyDynamicDetailRepository;
import com.youlu.campus.website.service.CompanyDynamicDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 动态详情服务实现类
 */
@Service
public class CompanyDynamicDetailServiceImpl implements CompanyDynamicDetailService {

    @Autowired
    private CompanyDynamicDetailRepository detailRepository;

    @Resource(name = "websiteMongoTemplate")
    private MongoTemplate mongoTemplate;

    @Override
    public CompanyDynamicDetail save(CompanyDynamicDetail detail) {
        if (StringUtils.isBlank(detail.getId())) {
            detail.setId(null);
            detail.setCreateTime(LocalDateTime.now());
        } else {
            detail.setUpdateTime(LocalDateTime.now());
        }
        return detailRepository.save(detail);
    }

    @Override
    public CompanyDynamicDetail findById(String id) {
        return detailRepository.findById(id).orElse(null);
    }

    @Override
    public void delete(String id) {
        detailRepository.deleteById(id);
    }

    @Override
    public List<CompanyDynamicDetail> findByPlatformAndPublishTimeBetween(PlatformType platform, LocalDateTime startOfMonth, LocalDateTime startOfNextMonth) {

        Query query = new Query().addCriteria(
                Criteria.where("platform").is(platform)
                        .and("publishTime").gte(startOfMonth).lt(startOfNextMonth)
        );

        List<CompanyDynamicDetail> dynamicDetails = mongoTemplate.find(query, CompanyDynamicDetail.class);

        return dynamicDetails;
    }

    @Override
    public Page<CompanyDynamicDetail> findByPage(CompanyDynamicDetailPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getTitle())) {
            query.addCriteria(Criteria.where("title").regex(pageQuery.getTitle(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getType())) {
            query.addCriteria(Criteria.where("type").is(pageQuery.getType()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, CompanyDynamicDetail.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<CompanyDynamicDetail> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, CompanyDynamicDetail.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public List<CompanyDynamicDetail> findByTypeAndTitleAndPlatformType(PlatformType platform, String type, String title) {
        Query query = new Query();
        if (StringUtils.isNotBlank(title)) {
            query.addCriteria(Criteria.where("title").regex(title, "i"));
        }
        if (StringUtils.isNotBlank(type)) {
            query.addCriteria(Criteria.where("type").is(type));
        }
        query.addCriteria(Criteria.where("platform").is(platform));
        // 应用排序
        query.with(Sort.by("publishTime").descending());
        List<CompanyDynamicDetail> list = mongoTemplate.find(query, CompanyDynamicDetail.class);
        return list;
    }

    @Override
    public CompanyDynamicDetail findFirstByPlatformTypeOrderByPublishTimeDesc(PlatformType platform) {
        return detailRepository.findFirstByPlatformOrderByPublishTimeDesc(platform);
    }
}